<template>
  <el-select
    :value="data"
    :multiple="multiple"
    :clearable="clearable"
    :filterable="filterable"
    :placeholder="placeholder"
    :size="size"
    :disabled="disabled"
    @change="change"
  >
    <el-option
      v-for="item in options"
      :key="item[propss.value]"
      :label="item[propss.label]"
      :value="item[propss.value]"
    ></el-option>
  </el-select>
</template>

<script>
/**
 * 接口获取数据自动生成element ui Select组件
 */
import request from "@/utils/request";
import apis from "@/components/Select/RemoteSelect/constants";
export default {
  props: {
    /**
     * 类型
     * 对应constants里每一个object的key值
     */
    varient: {
      type: String,
      required: true,
    },
    /**
     * @ignore
     * 详见element ui
     */
    size: {
      type: String,
      default: "small",
    },
    /**
     * @ignore
     * 详见element ui
     */
    multiple: {
      type: Boolean,
      default: false,
    },
    /**
     * @ignore
     * 详见element ui
     */
    clearable: {
      type: Boolean,
      default: true,
    },
    /**
     * @ignore
     * 详见element ui
     */
    filterable: {
      type: Boolean,
      default: true,
    },
    value: {
      type: [String, Number, Array],
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    /**
     * @ignore
     * 详见element ui
     */
    propss: {
      type: Object,
      default: () => ({
        label: "name",
        value: "id",
      }),
    },
    extraParams: {
      type: Object,
      default: () => ({}),
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
  },
  data() {
    return {
      options: [],
      data: this.value,
    };
  },
  watch: {
    value() {
      this.data = this.value;
    },
    extraParams() {
      this.getParams();
    },
  },
  created() {
    if (!this.varient) return;
    this.getParams();
  },
  methods: {
    async getParams() {
      const url = apis[this.varient].url;
      const res = await request({
        url,
        method: "get",
        params: { ...apis[this.varient].params, ...this.extraParams },
      });
      this.options = res.rows;
      this.$emit("afterLoad", this.options);
    },
    change(value) {
      const item = this.options.find(
        (item) => item[this.propss.value] === value
      );
      this.$emit("select", item);
      this.$emit("input", value);
    },
  },
};
</script>
